<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <!-- 标题根据id控制  插槽 -->
        <template v-slot:header>
          <span>{{editId ? $t('table.' + 'questionsEdit') : $t('table.' + 'questionsAdd')}}</span>
        </template>
        <el-form ref="form" :model="form" :rules="rules" label-width="120px">
          <!-- 学科 -->
          <el-form-item :label="$t('table.'+'Subject')" prop="subjectID">
            <el-select v-model="form.subjectID" placeholder="请选择" style="width: 400px" @change="subChange">
              <el-option v-for="item in subjectList" :key="item.value" :value="item.value" :label="item.label">
              </el-option>
            </el-select>
          </el-form-item>
          <!-- 目录 -->
          <el-form-item :label="$t('table.'+'Directorys')" prop="catalogID">
            <el-select v-model="form.catalogID" placeholder="请选择" style="width: 400px">
              <el-option v-for="item in catalogList" :key="item.value" :value="item.value" :label="item.label">
              </el-option>
            </el-select>
          </el-form-item>
          <!-- 企业 -->
          <el-form-item :label="$t('table.'+'Enterprises')" prop="enterpriseID">
            <el-select v-model="form.enterpriseID" placeholder="请选择" style="width: 400px">
              <el-option v-for="item in companyList" :key="item.id" :value="item.id" :label="item.company"></el-option>
            </el-select>
          </el-form-item>
          <!-- 城市 先选择城市  然后渲染区县 -->
          <el-form-item :label="$t('table.'+'City')" prop="city">
            <el-select v-model="form.province" placeholder="请选择" style="width: 195px; margin-right: 10px"
                       @change="provChange">
              <el-option v-for="(item, i) of provincesList" :key="i" :label="item" :value="item"></el-option>
            </el-select>
            <el-select v-model="form.city" placeholder="请选择" style="width: 195px">
              <el-option v-for="(item, i) of citysList" :key="i" :label="item" :value="item"></el-option>
            </el-select>
          </el-form-item>
          <!-- 方向 -->
          <el-form-item :label="$t('table.'+'Directions')" prop="direction">
            <el-select v-model="form.direction" placeholder="请选择" style="width: 400px">
              <el-option v-for="(item, i) in directionList" :key="i" :label="item" :value="item"></el-option>
            </el-select>
          </el-form-item>
          <!-- 题型 -->
          <el-form-item :label="$t('table.'+'QuestionType')">
            <!-- 单选组 -->
            <el-radio-group v-model="form.questionType" @change="quesTypeChange">
              <el-radio v-for="item in questionType" :key="item.value" :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 难度 -->
          <el-form-item :label="$t('table.'+'difficulty')">
            <!-- 单选组 -->
            <el-radio-group v-model="form.difficulty">
              <el-radio v-for="item in difficulty" :key="item.value" :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 题干 -->
          <el-form-item :label="$t('table.'+'stem')" prop="question">
            <div>
              <quill-editor ref="myLQuillEditor" v-model="form.question" :options="editorOption"></quill-editor>
            </div>
          </el-form-item>
          <!-- 单选 -->
          <el-form-item :label="$t('table.'+'options')" v-if="form.questionType === '1'">
            <el-row v-for="(item, index) in form.options" :key="index" class="check">
              <el-col :span="4" style="margin-right: -10px;">
                <el-radio @input="radioChange" v-model="radios" :label="item.code">{{ item.code }}：</el-radio>
              </el-col>
              <el-col :span="16">
                <el-input v-model="item.title" />
              </el-col>
              <el-col :span="4" style="margin-left: 10px">
                <imageUpload ref="image"></imageUpload>
              </el-col>
            </el-row>
          </el-form-item>
          <!-- 多选 -->
          <el-form-item :label="$t('table.'+'options')" v-if="form.questionType === '2'">
            <el-row v-for="(item, index) in form.options" :key="index" class="check">
              <el-col :span="4" style="margin-right: -10px;">
                <el-checkbox v-model="item.isRight">{{ item.code }}：</el-checkbox>
              </el-col>
              <el-col :span="16">
                <el-input v-model="item.title" />
              </el-col>
              <el-col :span="4" style="margin-left: 10px">
                <imageUpload ref="image"></imageUpload>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item>
            <el-button v-if="form.questionType !== '3'" type="danger" :disabled="form.questionType === '1'"
                       @click="clickCheckbox">{{$t('table.'+'addOptAnsewer')}}</el-button>
          </el-form-item>

          <el-form-item :label="$t('table.'+'videoURL')">
            <el-input style="width: 400px" v-model="form.videoURL"></el-input>
          </el-form-item>
          <el-form-item :label="$t('table.'+'answer')" prop="answer">
            <quill-editor ref="myLQuillEditor" v-model="form.answer" :options="editorOption">
            </quill-editor>
          </el-form-item>
          <el-form-item :label="$t('table.'+'Remarks')">
            <el-input type="textarea" :rows="2" placeholder="请输入内容" v-model="form.remarks" style="width: 400px">
            </el-input>
          </el-form-item>
          <el-form-item :label="$t('table.'+'tags')">
            <el-select v-model="form.tags" placeholder="请选择" multiple  style="width: 400px" filterable allow-create>
              <el-option v-for="item in tagsList" :key="item.value" :value="item.label" :label="item.label"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button :type="showBtnType" @click="submit">{{editId ? $t('table.' + 'sureEdit') : $t('table.' + 'sureAdd')}}</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>
// 引入上传图片的组件
import imageUpload from '../components/imageUpload.vue'
// 引入富文本编辑器  引入样式
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
// 引入简单学科列表Api
import { simple as subSimple } from '@/api/hmmm/subjects'
// 引入简单目录列表Api
import { simple as catalogSimple } from '@/api/hmmm/directorys'
// 引入获取公司列表Api
import { list as companyListApi } from '@/api/hmmm/companys'
// 引入获取城市列表Api
import { provinces as provincesApi, citys as citysApi } from '@/api/hmmm/citys'
// 引入枚举  方向，难度，题型
import {
  direction as directionList,
  difficulty,
  questionType
} from '@/api/hmmm/constants'
// 引入获取标签列表Api
import { simple as tagsSimple } from '@/api/hmmm/tags'
// 引入  添加\修改\详情 试题Api,            list as quesListApi
import {
  add as addApi,
  detail as detailApi,
  update as updateApi
  // list as quesListApi
} from '@/api/hmmm/questions'
export default {
  name: 'questionNew',
  components: {
    // 富文本编辑器
    quillEditor,
    // 图片上传
    imageUpload
  },
  data () {
    return {
      // 表单数据
      form: {
        subjectID: '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业
        province: '', // 城市
        city: '', // 地区
        direction: '', // 方向
        questionType: '1', // 题型
        difficulty: '1', // 难度
        question: '', // 题干
        options: [
          // 选项
          { isRight: false, code: 'A', title: '', img: '' },
          { isRight: false, code: 'B', title: '', img: '' },
          { isRight: false, code: 'C', title: '', img: '' },
          { isRight: false, code: 'D', title: '', img: '' }
        ],
        videoURL: '', // 解析视频
        answer: '', // 答案解析
        remarks: '', // 题目备注
        tags: '' // 试题标签
      },
      // 校验规则
      rules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'change' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ],
        city: [{ required: true, message: '请选择地区', trigger: 'change' }],
        direction: [
          { required: true, message: '请选择方向', trigger: 'change' }
        ],
        question: [{ required: true, message: '请输入题干', trigger: 'blur' }],
        answer: [
          { required: true, message: '请输入答案解析', trigger: 'blur' }
        ]
      },
      // 富文本编辑器配置 配置功能
      editorOption: {
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
            [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表
            ['blockquote', 'code-block'], // 引用  代码块
            ['image', 'link'] // 链接、图片、视频
          ]
        },
        placeholder: '' // 提示符
      },
      directionList, // 方向列表
      tagsList: [], // 标签列表
      difficulty, // 难度
      questionType, // 题型
      subjectList: [], // 学科列表
      catalogList: [], // 目录列表
      companyList: [], // 公司列表
      provincesList: [], // 城市列表
      citysList: [], // 地区列表
      radios: '' // 单选选择
    }
  },
  async created () {
    // 获取试题列表的,开发时候用到
    // const { data } = await quesListApi()
    // console.log(data.items)
    // 获取详情  有id的时候才调用
    if (this.editId) {
      this.getDetailList()
    }
    // 获取学科列表
    this.getsubjectList()
    // 获取公司列表
    this.getcompanyList()
    // 获取城市列表
    this.getProvinceList()
    // 滚动
    // this.scroll()
  },
  mounted () {
    this.scroll()
  },
  computed: {
    // 根据id控制标题
    // showTitle () {
    //   return this.editId ? $t('table.' + 'videoURL' + '：') : '试题录入'
    // },
    // // 根据id控制按钮的文字
    // showBtnTitle () {
    //   return this.editId ? '确认修改' : '确认添加'
    // },
    // 根据id控制按钮的样式
    showBtnType () {
      return this.editId ? 'success' : 'primary'
    },
    // 修改时候带的id
    editId () {
      return this.$route.query.id || ''
    },
    routerJump () {
      return this.$route.query.routerJump || ''
    }

  },
  methods: {
    mounted () {
      this.scroll()
    },
    /**
     * 防止滚动
     */
    scroll () {
      this.$refs.myLQuillEditor.quill.enable(false) // 进入页面失去焦点
      setTimeout(() => {
        this.$refs.myLQuillEditor.quill.enable(true) // 两秒后点击可获取焦点
      }, 2000)
    },
    /**
     * 获取学科列表信息
     */
    async getsubjectList () {
      const { data } = await subSimple()
      this.subjectList = data
    },
    /**
     * 学科改变的时候，重新调用获取目录的标签的接口
     */
    subChange () {
      // 先清空  因为学科更换就会更改标签
      this.form.tags = ''
      this.form.catalogID = ''
      // 获取目录
      this.getcatalogList()
      // 获取标签
      this.getTagsList()
    },
    /**
     * 获取目录列表信息
     */
    async getcatalogList (subID) {
      const params = { subjectID: subID || this.form.subjectID }
      const { data } = await catalogSimple(params)
      this.catalogList = data
    },
    /**
     * 获取公司列表信息
     */
    async getcompanyList () {
      // 需要再全部展示  获取所有的数据 自定义参数
      const params = { page: 1, pagesize: 1000 }
      const { data } = await companyListApi(params)
      this.companyList = data.items
    },
    /**
     * 获取城市列表信息
     */
    getProvinceList () {
      const data = provincesApi()
      this.provincesList = data
    },
    /**
     * 获取区县列表信息
     */
    getCitysList () {
      const data = citysApi(this.form.province)
      // 先清空  因为城市更换就会更改区县
      this.form.city = ''
      this.citysList = data
    },
    /**
     * 再点击城市的时候，需要重新获取区县
     */
    provChange () {
      this.getCitysList()
    },
    /**
     * 获取标签列表信息
     */
    async getTagsList (subID) {
      const params = { subjectID: subID || this.form.subjectID }
      const { data } = await tagsSimple(params)
      // console.log(data)
      this.tagsList = data
    },
    /**
     * 多选新增选项和答案
     */
    clickCheckbox () {
      // 通过ascii码自动新增选项字母
      // 先获取到最后一个选项的code字母
      const nowWord = this.form.options[this.form.options.length - 1].code
      // charCodeAt() 方法可返回指定位置的字符的 Unicode 编码
      // fromCharCode（）将 Unicode 编码转为一个字符: +1为下一个
      const newWord = String.fromCharCode(nowWord.charCodeAt() + 1)
      // 创建新的选项
      const newObj = { isRight: false, code: newWord, title: '', img: '' }
      // 推入options
      this.form.options.push(newObj)
    },
    /**
     * 更换题型的时候，重置选项数据
     */
    quesTypeChange () {
      // 先把单选选择清除
      this.radios = ''
      // 再给默认数据
      this.form.options = [
        { isRight: false, code: 'A', title: '', img: '' },
        { isRight: false, code: 'B', title: '', img: '' },
        { isRight: false, code: 'C', title: '', img: '' },
        { isRight: false, code: 'D', title: '', img: '' }
      ]
    },
    /**
     * 单选点击的时候
     */
    radioChange (val) {
      // 遍历选项  找到与点击的选项对应的，改为true
      this.form.options.forEach((item) => {
        // 先把每一项都改为fa
        item.isRight = false
        if (item.code === val) {
          item.isRight = true
        }
      })
    },
    /**
     *根据id获取详情数据并回显
     */
    async getDetailList () {
      // 根据id拿到详细数据
      const { data } = await detailApi({ id: this.editId })
      data.options = data.options.sort(function (a, b) {
        if (a.code < b.code) {
          return -1
        }
        if (a.code > b.code) {
          return 1
        }
        // names must be equal
        return 0
      })
      // console.log(data, '回显第一时间的数据')
      // 遍历详细数据，然后遍历，因为返回来的数据是0和1，需要变为true和false
      data.options.forEach((item, index) => {
        item.isRight = !!item.isRight
        if (item.isRight) {
          // 把单选的结果回显
          this.radios = item.code
        }
        if (item.img) {
          this.$refs.image[index].filelist.push({ url: item.img })
        }
      })
      this.$nextTick(async () => {
        // 请求目录信息
        await this.getcatalogList(data.subjectID)
        if (data.tags) {
        // 先把字符串,转为数组，方便遍历
          data.tags = data.tags.split(',')
          // 获取到所有的标签
          await this.getTagsList(data.subjectID)
        }
        this.$nextTick(() => {
          this.form = data
        })
      })
    },
    /**
     * 清除数据专用
     */
    clearFrom () {
      // 清除数据 和 校验
      this.$refs.form.resetFields()
      this.form = {
        subjectID: '',
        catalogID: '',
        enterpriseID: '',
        province: '',
        city: '',
        direction: '',
        questionType: '1',
        difficulty: '1',
        question: '',
        options: [
          { isRight: false, code: 'A', title: '', img: '' },
          { isRight: false, code: 'B', title: '', img: '' },
          { isRight: false, code: 'C', title: '', img: '' },
          { isRight: false, code: 'D', title: '', img: '' }
        ],
        videoURL: '',
        answer: '',
        remarks: '',
        tags: ''
      }
      // 清空图片
      this.$refs.image.forEach((item) => {
        item.filelist[0] = {}
      })
    },
    /**
     * 点击添加或者修改按钮
     */
    submit () {
      // 兜底校验
      this.$refs.form.validate((flag) => {
        if (!flag) return
        // 需要把组件里的图片信息赋值给options里在提交
        this.form.options.forEach(async (item, index) => {
          await this.$nextTick()
          item.img = this.$refs.image[index]?.filelist[0]?.url || ''
        })
        // 判断如果标签有值
        if (this.form.tags) {
          // 把多选的数组转为字符串
          this.form.tags = this.form.tags.join()
        }
        this.$nextTick(async () => {
          // 如果有id
          if (this.editId) {
          // 修改接口
            await updateApi(this.form)
            this.$message.success('修改成功')
          } else {
          // 添加接口
            // console.log(this.form, '添加提交的数据')
            await addApi(this.form)
            this.$message.success('添加成功')
          }
          // 清除数据
          this.clearFrom()
          if (this.routerJump === '2') {
            this.$router.push('/questions/choice')
            // 跳转
          } else {
            // 跳转
            this.$router.push('/questions/list')
          }
        })
      })
    }
  }
}
</script>

<style  lang='scss' scoped >
.el-form {
  ::v-deep {
    .ql-toolbar .ql-snow {
      padding: 0 8px;
    }
    .ql-editor {
      height: 200px;
    }
    .check {
      width: 400px;
      display: flex;
      align-items: center;
      .el-input {
        margin-top: 20px;
        margin-bottom: 20px;
      }
    }
    .el-upload--picture-card,
    .el-upload-list__item {
      width: 100px;
      height: 60px;
      line-height: 60px;
    }
  }
}
</style>
